<template>
	<view class="sort-container">
		<view class="sort-options">
			<view v-for="sort in sortOptions" :key="sort[format.id]" class="sort-option x-f">
				<text>{{ sort[format.name] }}</text>
				<view>
					<text class="order" @tap="handleOrderClick(sort, item)" v-for="(item, index) in sortFields"
						:key="index"
						:class="{ 'selected': defaultSort === sort[format.id] && selectSort[format.value] === item[format.value] }">
						{{ item[format.text] }}
					</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts" name="m-sort">
	// 定义格式类型接口
	interface Format {
		id : string;
		name : string;
		text : string;
		value : string;
	}

	// 定义排序字段项接口
	interface SortFieldItem {
		[key : string] : string;
	}

	// 定义排序选项接口
	interface SortOption {
		[key : string] : any;
	}

	// 定义组件要发射的事件
	const emit = defineEmits<{
		(e : 'change', data : { sort : SortOption; item : SortFieldItem }) : void;
	}>();

	// 定义组件属性，使用类型断言解决转换问题
	const props = defineProps({
		sortOptions: {
			type: Array as () => SortOption[],
			default: () => []
		},
		sortFields: {
			type: Array as () => SortFieldItem[],
			default: () => [
				{ text: '升序', value: 'ASC' },
				{ text: '降序', value: 'DESC' }
			]
		},
		defaultSort: {
			// 关键修复：使用unknown作为中间类型进行转换
			type: [String, Number] as unknown as () => string | number,
			default: ''
		},
		selectSort: {
			type: Object as () => Record<string, any>,
			default: () => ({})
		},
		format: {
			type: Object as () => Format,
			default: () => ({
				id: 'id',
				name: 'name',
				text: 'text',
				value: 'value',
			})
		}
	});

	// 处理排序点击事件
	const handleOrderClick = (sort : SortOption, item : SortFieldItem) => {
		emit('change', {
			sort,
			item
		});
	};
</script>

<style lang="scss">
	.sort-container {
		.sort-options {
			.sort-option {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 10upx 10upx;
				border-bottom: 1px solid #f3f3f3;

				.order {
					padding: 0 20px;
					cursor: pointer;
					color: #5d5d5d;

					&:first-child {
						border-right: 1px solid #f3f3f3;
					}

					&.selected {
						font-weight: bold;
						color: #2aaa7d;
					}
				}
			}
		}
	}
</style>